package cn.edu.scau.cmi.wuzhenxin.comprehension.client;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;

import cn.edu.scau.cmi.wuzhenxin.comprehension.dao.StudentDAO;
import cn.edu.scau.cmi.wuzhenxin.comprehension.dao.TeacherDAO;
import cn.edu.scau.cmi.wuzhenxin.comprehension.domain.Student;
import cn.edu.scau.cmi.wuzhenxin.comprehension.domain.Teacher;
import cn.edu.scau.cmi.wuzhenxin.comprehension.util.ComprehensionApplicationContextUtil;
import cn.edu.scau.cmi.wuzhenxin.comprehension.util.ScauCmiHibernateSessionFactoryUtil;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

public class ComprehensionHibernateSpringController {

	@FXML
	private TextArea textArea_info;
	@FXML
	private Button btn_show;
	
	@FXML
	private Button btn_stuSave;
	@FXML
	private Button btn_tchSave;
	@FXML
	private TextField teacherField;
	@FXML
	private TextField studentField;
	//spring注入dao对象
	ApplicationContext applicationContext = ComprehensionApplicationContextUtil.getApplicationContext();
	StudentDAO studentDAO = (StudentDAO) applicationContext.getBean("studentDao");
	TeacherDAO teacherDAO = (TeacherDAO) applicationContext.getBean("teacherDao");
	Session session;
	Teacher teacher;
	Student student;
	
	public void newStudent(ActionEvent event) {
		Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		student=new Student();
		student.setName(studentField.getText().toString());
		student.setTeacher(teacher);

		studentDAO.save(student);
		
		transaction.commit();
		session.close();
		textArea_info.setText("学生保存成功");
	}
	
	public void newTeacher(ActionEvent event) {
		Session session = ScauCmiHibernateSessionFactoryUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		teacher=new Teacher();
		System.out.println(teacherField.getText().toString());
		teacher.setName(teacherField.getText().toString());
		teacherDAO.save(teacher);
		
		transaction.commit();
		session.close();
		textArea_info.setText("老师保存成功");
	}

	public void listStudents(ActionEvent event) {
	textArea_info.clear();

	List students = studentDAO.findAll();
	Iterator<?> studentIterator = students.iterator();
	while(studentIterator.hasNext()){
		Student student = (Student) studentIterator.next();
		textArea_info.appendText("学生："+student.getName() + "  导师：" + student.getTeacher().getName() + "\n");
	}
}
}